package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Integer[].class)         //javatype
@MappedJdbcTypes(JdbcType.VARCHAR)    //jdbctype
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 输入映射过程
     * 占位符的序号 select xxx from xxx where id = ? and password = ? and age=?
     * 第三个参数：输入映射传入的参数 → 和数据库能够对应的JavaType不匹配 → 你需要做一个格式转换
     */
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {
        //Integer[] → String
        String value = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,value);
    }

    /**
     * 输出映射的过程 → 获得查询的结果 → 通过resultSet
     */
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    private Integer[] transfer(String result) {
        //String → Integer[]
        Integer[] integers = new Integer[0];
        if (result != null && !"".equals(result)){
            try {
                integers = objectMapper.readValue(result,Integer[].class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return integers;
        }
        return integers;
    }
}
